<template>
  <div class="replay-wrap">
    <table>
      <tr>
        <td>
          <div>
            第<InputNumber
              size="small"
              class="w60"
              v-model="selectWeek"
            ></InputNumber
            >周复盘
            <Button size="small" type="primary" @click="doReplayAnaly"
              >生成周复盘结果</Button
            >
            <Button
              class="mar10l"
              size="small"
              type="primary"
              @click="analyAllCounts"
              >总字数</Button
            >
            <template v-if="isShowReplay">
              ---
              <Button size="small" type="primary" @click="doExport"
                >导出复盘记录</Button
              >
            </template>
          </div>
          <div class="subtab mar10t">
            <a :class="{ cur: subTab === 1 }" @click="subTab = 1"
              >周复盘统计信息</a
            >
            ---
            <a :class="{ cur: subTab === 3 }" @click="subTab = 3">导出</a>
            ---
            <a :class="{ cur: subTab === 2 }" @click="subTab = 2">设置</a>
            ---
            <Checkbox v-model="isSortNormal">成员默认排序</Checkbox>
            --
            <Checkbox v-model="isShowLeavePeople">显示离开人员</Checkbox>
          </div>
        </td>
        <td>
          <p>本周复盘问题(用于过滤)：</p>
          <textarea
            v-model="sourceQuestions"
            style="width: 400px; height: 50px"
          ></textarea>
        </td>
      </tr>
    </table>
    <template v-if="subTab === 1">
      <p>周复盘统计</p>
      <table class="table" v-show="!isShowNumsList">
        <tr>
          <th width="40">序号</th>
          <th width="100">QQ</th>
          <th width="200">昵称</th>
          <th :width="isTimeWide ? 150 : 85">
            提交时间
            <TableSort
              :order="getSortOrder('time')"
              @changeSort="changeSort('time', $event)"
            ></TableSort>
            <TablePoptip>
              <ul>
                <li>
                  <a @click="copyStatus">复制状态到剪贴板</a>
                </li>
                <li>
                  <a @click="isTimeWide = !isTimeWide">更改时间宽度</a>
                </li>
              </ul>
            </TablePoptip>
          </th>
          <th class="td-answer text-left">
            <select v-model="selectQuestion">
              <option value="all">筛选问题</option>
              <option
                v-for="(name, index) in questions"
                :key="'ques_' + index"
                :value="name"
              >
                {{ name }}
              </option>
            </select>
            <span>
              {{ subQuestions[selectQuestion] }}
            </span>
            <TablePoptip>
              <ul>
                <li>
                  <a @click="copyAnswer">复制答案</a>
                </li>
              </ul>
            </TablePoptip>
          </th>
          <th class="text-left" v-if="isShowOperate">
            <Checkbox v-model="isShowMoreOperate">操作</Checkbox>
          </th>
        </tr>
        <tr v-for="(item, index) in showList" :key="'replay_' + index">
          <td class="center">{{ index + 1 }}</td>
          <td>{{ item.qq }}</td>
          <td>{{ item.nickname }}</td>
          <td :class="{ delay: item.isDelay }">{{ item.time }}</td>
          <td v-html="showContent(answers[item.qq][selectQuestion])"></td>
          <td class="center" v-if="isShowOperate">
            <a @click="showPeopleReplay(item)">查看</a>
            <template v-if="isShowMoreOperate">
              <Tooltip transfer content="手动导入复盘">
                <a class="mar10l" @click="startImportWork(item)">导入</a>
              </Tooltip>
              <Tooltip transfer content="复制到剪贴板,用于在补丁文件中">
                <a class="mar10l red" @click="copyWork(item)">复制</a>
              </Tooltip>
            </template>
          </td>
        </tr>
      </table>

      <table
        class="table table-nums"
        style="width: 1800px"
        v-show="isShowNumsList"
      >
        <tr>
          <th width="40">序号</th>
          <th width="100">QQ</th>
          <th width="200">昵称</th>
          <th width="80">
            感谢次数
            <TablePoptip>
              <ul>
                <li>
                  <a @click="copyThankNums">复制</a>
                </li>
              </ul>
            </TablePoptip>
          </th>
          <th width="80">
            总字数
            <TablePoptip>
              <ul>
                <li>
                  <a @click="copyNums">复制字数到剪贴板</a>
                </li>
              </ul>
            </TablePoptip>
          </th>
          <th width="80" v-for="(w, wIndex) in weeks" :key="'w_' + wIndex">
            W{{ w }}
          </th>
        </tr>
        <tr v-for="(item, index) in numsList" :key="'replay_num_' + index">
          <td class="center">{{ index + 1 }}</td>
          <td>{{ item.qq }}</td>
          <td>{{ item.nickname }}</td>
          <td @click="showThankList(item)">{{ item.thankCount }}</td>
          <td>{{ item.total }}</td>
          <td v-for="(w, index2) in weeks" :key="'w_' + index + '_' + index2">
            {{ item["w" + w] }}
          </td>
        </tr>
      </table>
    </template>
    <template v-if="subTab === 2">
      复盘识别标识：<input type="text" v-model="headerKey" />
      <br />
      标识开头：<input type="text" v-model="startKey" /> 标识结束：<input
        type="text"
        v-model="endKey"
      />
    </template>
    <template v-if="subTab === 3">
      <ExportReplay :analyResult="showList"></ExportReplay>
    </template>
    <ModalReplays
      :replayItem="replayItem"
      :questions="allQuestions"
      :subQuestions="subQuestions"
      :list="thankReplayList"
      :tagNames="tagNames"
      v-if="isShowReplayFilter"
      @close="isShowReplayFilter = false"
    ></ModalReplays>
    <ModalImportWork
      title="导入复盘"
      :importMember="importMember"
      v-if="isImportWork"
      @close="isImportWork = false"
      @save="doImportWork"
    ></ModalImportWork>
  </div>
</template>

<script>
import {
  cloneObj,
  format2Html,
  getDateByStr,
  splitPerson,
  filterReplayQuestions,
  saveTXT,
  copy2Clipboard,
} from "js/utils.js";
import ModalReplays from "@/components/ModalReplays.vue";
import ModalImportWork from "@/components/ModalImportWork.vue";
import ExportReplay from "@/components/ExportReplay.vue";
const dayjs = require("dayjs");

export default {
  data() {
    return {
      subTab: 1,
      headerKey: "中国思想史6队读书周复盘",
      startKey: "WK",
      endKey: "#",
      selectWeek: 1,
      sourceQuestions: "", // 本周复盘问题
      isShowReplay: false, // 是否分析到了结果
      searchList: [],
      allQuestions: [],
      questions: [],
      subQuestions: {},
      answers: {},
      selectQuestion: "all",
      isTimeWide: true,
      sortKey: "time", // 排序key
      sortOrder: "asc", // 排序order
      isSortNormal: false, // 按人员序号排序
      isShowLeavePeople: false, // 显示离开人员
      isShowMoreOperate: false, // 显示更多操作

      isShowReplayFilter: false,
      replayItem: null,

      importMember: null,
      importMemberIndex: -1,
      isImportWork: false,

      numsList: [],
      isShowNumsList: false,
      thankReplayList: [],
      tagNames: [],
    };
  },
  computed: {
    showList() {
      let list = cloneObj(this.searchList);
      if (!this.isShowLeavePeople) {
        list = list.filter((item) => !item.isLeave);
      }
      if (this.sortKey === "time") {
        list.sort((a, b) => {
          if (a.time && b.time) {
            if (this.sortOrder === "asc") {
              return dayjs(a.time).isAfter(b.time) ? 1 : -1;
            }
            return dayjs(a.time).isBefore(b.time) ? 1 : -1;
          }
          if (!a.time && !b.time) {
            return a.no > b.no ? 1 : -1;
          }
          if (!a.time) {
            return 1;
          }
          return -1;
        });
      } else if (this.sortKey === "no") {
        list.sort((a, b) => (a.no > b.no ? 1 : -1));
      }
      return list;
    },
    isShowOperate() {
      return !this.selectQuestion || this.selectQuestion === "all";
    },
    members() {
      return this.$store.getters.getMembers();
    },
    weeks() {
      let list = [];
      for (let w = 1; w <= 16; w++) {
        list.push(w);
      }
      return list;
    },
  },
  watch: {
    isShowOperate(newval, oldval) {
      if (newval) {
        this.isTimeWide = true;
      }
      if (oldval) {
        this.isTimeWide = false;
      }
    },
    isSortNormal(newval) {
      if (newval) {
        this.sortKey = "no";
      } else {
        this.sortKey = "time";
        this.sortOrder = "asc";
      }
    },
  },
  methods: {
    initData() {
      let week = this.$store.getters.getStorageVal("week");
      this.selectWeek = week;
    },
    // 点击分析
    async doReplayAnaly() {
      let members = this.$store.getters.getMembers();
      if (members.length === 0) {
        this.$global.log("请先导入成员");
        return;
      }
      if (!this.selectWeek) {
        this.$global.log("请输入周数");
        return;
      }
      let text = await this.$global.getFileText("small");
      if (!text) {
        this.$global.log("请选择小群文件");
        return;
      }
      this.isShowNumsList = false;
      let isHaveResult = false;
      let qqObj = {};
      let nickNameObj = {};
      for (let i = 0, n = members.length; i < n; i++) {
        let item = members[i];
        qqObj[item.qq] = item;
        nickNameObj[item.nickname] = item;
      }
      let allList = splitPerson(text);
      let headerKey = this.headerKey;
      let searchKey = this.startKey + this.selectWeek + this.endKey;
      let searchList = [];
      for (let i = 0, n = allList.length; i < n; i++) {
        let item = allList[i];
        let content = item.content;
        if (!content) {
          continue;
        }
        if (item.qq) {
          if (!qqObj[item.qq]) {
            continue;
          }
          if (item.nickname !== qqObj[item.qq].nickname) {
            item.nickname = qqObj[item.qq].nickname;
          }
        } else {
          if (!nickNameObj[item.nickname]) {
            continue;
          }
        }
        if (content.includes(headerKey) && content.includes(searchKey)) {
          isHaveResult = true;
          if (!item.qq) {
            item.qq = nickNameObj[item.nickname].qq;
          }
          item.isLeave = qqObj[item.qq].isLeave;
          item.no = qqObj[item.qq].no;
          searchList.push(item);
        }
      }
      this.endDate = "";
      for (let i = 0, n = searchList.length; i < n; i++) {
        let item = searchList[i];
        searchList[i] = this.getResultItem(item);
      }
      searchList.sort((a, b) => (a.time > b.time ? 1 : -1));
      let obj = {};
      for (let i = searchList.length - 1; i >= 0; i--) {
        let item = searchList[i];
        if (obj[item.qq]) {
          searchList.splice(i, 1);
        } else {
          obj[item.qq] = 1;
        }
      }
      let resultNicknames = searchList.map((item) => item.nickname);
      let noResult = members.filter(
        (item) => !resultNicknames.includes(item.nickname)
      );
      for (let i = 0, n = noResult.length; i < n; i++) {
        let item = noResult[i];
        searchList.push({
          qq: item.qq,
          nickname: item.nickname,
          isLeave: item.isLeave,
          no: item.no,
        });
      }
      this.checkQuestions(searchList);
      this.searchList = searchList;
      this.isShowReplay = true;
      new this.$tableSelect(".replay-wrap .table");
      if (isHaveResult) {
        this.$store.commit("saveStorage", {
          tag: "week",
          num: this.selectWeek,
        });
      }
    },
    getResultItem(item) {
      let isDelay = false;
      if (item.time) {
        let addDate = getDateByStr(item.time);
        if (!this.endDate) {
          let addTime = new Date(item.time);
          let day = addTime.getDay();
          let checkDay = (7 - day) % 7;
          if (checkDay > 0) {
            let nextDate = new Date(
              addTime.getTime() + checkDay * 24 * 60 * 60 * 1000
            );
            this.endDate = getDateByStr(nextDate);
          } else {
            this.endDate = addDate;
          }
        }
        if (addDate > this.endDate) {
          isDelay = true;
        }
      }
      item.isDelay = isDelay;
      return item;
    },
    // 检测问题
    checkQuestions(searchList) {
      let obj = {};
      let subObj = {};
      let sourceQuestions = this.sourceQuestions;
      let saveKey = "wk" + this.selectWeek + "q";
      let searchKey = this.startKey + this.selectWeek + this.endKey;
      let isHaveSourceQuestion = false;
      if (sourceQuestions && sourceQuestions.indexOf(searchKey) === -1) {
        sourceQuestions = "";
        this.$Message.error("当前复盘问题输入框与选择的不是同一周");
      }
      if (sourceQuestions) {
        localStorage.setItem(saveKey, sourceQuestions);
      } else {
        sourceQuestions = localStorage.getItem(saveKey);
      }
      let baseQuestions = [];
      if (sourceQuestions) {
        let qas = filterReplayQuestions(sourceQuestions);
        for (let i = 0, n = qas.length; i < n; i++) {
          let question = qas[i].question;
          let subQuestion = qas[i].answer;
          obj[question] = 0;
          subObj[question] = subQuestion.trim();
        }
        baseQuestions = qas.map((item) => item.question);
        isHaveSourceQuestion = qas.length > 0;
      }
      for (let i = 0, n = searchList.length; i < n; i++) {
        let item = searchList[i];
        let content = item.content;
        let answerObj = {};
        if (content) {
          let qas = filterReplayQuestions(content, baseQuestions);
          for (let j = 0, m = qas.length; j < m; j++) {
            let question = qas[j].question;
            let answer = qas[j].answer;
            let subQuestion = subObj[question];
            if (subQuestion && answer) {
              if (subQuestion.indexOf("\n") > -1) {
                let subArr = subQuestion.split(/[\n|\s|\x20]/);
                for (let subStr of subArr) {
                  subStr = subStr.trim();
                  if (subStr && answer.indexOf(subStr) > -1) {
                    answer = answer.replace(subStr, "");
                  }
                }
              } else if (answer.indexOf(subQuestion) > -1) {
                answer = answer.replace(subQuestion, "");
              }
            }
            if (obj[question] === undefined) {
              obj[question] = 0;
            }
            if (answer) {
              obj[question] += 1;
            }
            answerObj[question] = answer;
          }
        }
        this.answers[item.qq] = answerObj;
        this.$set(this.answers, item.qq, answerObj);
      }
      let questions = [];
      let allQuestions = [];
      let ignoreQuestions = ["【全面复盘必交】", "【群昵称】"];
      for (let key in obj) {
        let val = obj[key];
        if (val === 0) {
          continue;
        }
        allQuestions.push(key);
        if (ignoreQuestions.includes(key)) {
          continue;
        }
        questions.push(key);
      }
      this.allQuestions = allQuestions;
      this.questions = questions;
      this.subQuestions = subObj;
    },
    // 更改排序
    changeSort(key, order) {
      this.sortKey = key;
      this.sortOrder = order;
    },
    // 获取排序order
    getSortOrder(key) {
      if (key === this.sortKey) {
        return this.sortOrder;
      }
      return "";
    },
    // 导入复盘
    doImportWork(obj) {
      let time = obj.time;
      let content = obj.content;

      let item = this.importMember;
      let index = this.importMemberIndex;
      let title = `${time} ${item.nickname}(${item.qq})`;

      item.time = time;
      item.count = content.length;
      item.title = title;
      item.content = content;

      let resultItem = this.getResultItem(item);
      this.searchList[index] = resultItem;
      this.$set(this.searchList, index, this.searchList[index]);
      this.checkQuestions(this.searchList);
      this.isImportWork = false;
    },
    startImportWork(item) {
      let index = -1;
      for (let i = 0, n = this.searchList.length; i < n; i++) {
        let item2 = this.searchList[i];
        if (item.qq === item2.qq) {
          index = i;
          break;
        }
      }
      // 准备导入
      this.importMember = this.searchList[index];
      this.importMemberIndex = index;
      this.isImportWork = true;
    },
    // 导出所有人的题目和答案
    doExport() {
      let str = "";
      for (let i = 0, n = this.searchList.length; i < n; i++) {
        let item = this.searchList[i];
        let title = item.title || "";
        let nickname = item.nickname;
        let content = item.content || "";
        str += `@${nickname}\n${title.trim()}\n${content.trim()}\n\n`;
      }
      saveTXT(str, "WK" + this.selectWeek + ".txt");
    },
    showContent(content) {
      if (!content) {
        return "";
      }
      let str = content;
      str = str.trim();
      str = format2Html(str);
      return str;
    },
    // 查看复盘
    showPeopleReplay(item) {
      if (!item.content) {
        this.$Message.info("当前无提交内容");
        return;
      }
      this.replayItem = item;
      this.isShowReplayFilter = true;
    },
    // 复制作业
    copyWork(item) {
      if (!item.time) {
        this.$Message.info("无作业可复制");
        return;
      }
      let str = "";
      let title = item.title || "";
      let nickname = item.nickname;
      let content = item.content || "";
      str += `${title}\n${content.trim()}\n\n`;
      copy2Clipboard(str);
      this.$Message.info("复制成功!");
    },
    // 复制状态
    copyStatus() {
      let str = "";
      for (let i = 0, n = this.showList.length; i < n; i++) {
        let item = this.showList[i];
        let time = item.firstSubmitTime || item.time;
        if (!time) {
          str += " ";
        } else if (item.isDelay) {
          str += `2`;
        } else {
          str += "1";
        }
        str += "\n";
      }
      copy2Clipboard(str);
      this.$Message.info("复制成功!");
    },
    // 复制当前选择的答案
    copyAnswer() {
      let str = "";
      let selectQuestion = this.selectQuestion;
      if (selectQuestion === "all") {
        for (let i = 0, n = this.showList.length; i < n; i++) {
          let item = this.showList[i];
          let nickname = item.nickname;
          let title = item.title || "";
          let content = item.content || "";
          str += `@${nickname}\n${title.trim()}\n${content.trim()}\n\n`;
        }
      } else {
        let subQuestion = this.subQuestions[selectQuestion];
        str += `${selectQuestion}${subQuestion}\n`;
        for (let i = 0, n = this.showList.length; i < n; i++) {
          let item = this.showList[i];
          let nickname = item.nickname;
          let title = item.title || "";
          let answer = this.answers[item.qq][selectQuestion].trim();
          str += `@${nickname}\n${answer}\n---\n`;
        }
      }
      copy2Clipboard(str);
      this.$Message.info("复制成功!");
    },
    // 分析总字数
    async analyAllCounts() {
      let members = this.$store.getters.getMembers();
      if (members.length === 0) {
        this.$global.log("请先导入成员");
        return;
      }
      let text = await this.$global.getFileText("small");
      if (!text) {
        this.$global.log("请选择小群文件");
        return;
      }
      let qqObj = {};
      let nickNameObj = {};
      let thanksObj = {};
      let allSubNames = [];
      for (let i = 0, n = members.length; i < n; i++) {
        let item = members[i];
        qqObj[item.qq] = item;
        nickNameObj[item.nickname] = item;
        if (item.subnames) {
          let subnames = item.subnames.split(",");
          subnames.map((name) => {
            thanksObj[name] = {
              qq: item.qq,
              nickname: item.nickname,
              count: 0,
              list: [],
            };
            allSubNames.push(name);
          });
        }
      }

      let allList = splitPerson(text);
      let headerKey = this.headerKey;
      let searchList = [];
      let memberNumsObj = {};
      for (let i = 0, n = allList.length; i < n; i++) {
        let item = allList[i];
        let content = item.content;
        if (!content) {
          continue;
        }
        if (item.qq) {
          if (!qqObj[item.qq]) {
            continue;
          }
          if (item.nickname !== qqObj[item.qq].nickname) {
            item.nickname = qqObj[item.qq].nickname;
          }
        } else {
          if (!nickNameObj[item.nickname]) {
            continue;
          }
        }
        if (content.indexOf(this.startKey) === -1) {
          continue;
        }
        for (let j = 0, m = allSubNames.length; j < m; j++) {
          let name = allSubNames[j];
          if (
            thanksObj[name].qq === item.qq ||
            thanksObj[name].nickname === item.nickname
          ) {
            continue;
          }
          if (content.includes(name)) {
            thanksObj[name].count += 1;
            thanksObj[name].list.push({
              title: item.title,
              content: item.content,
            });
          }
        }
        let contLen = content.length;
        for (let w = 1; w <= 16; w++) {
          let searchKey = this.startKey + w + this.endKey;
          if (content.includes(searchKey)) {
            if (!item.qq) {
              item.qq = nickNameObj[item.nickname].qq;
            }
            if (!memberNumsObj[item.qq]) {
              memberNumsObj[item.qq] = {
                qq: item.qq,
                nickname: item.nickname,
                isLeave: qqObj[item.qq].isLeave,
              };
            }
            memberNumsObj[item.qq]["w" + w] = contLen;
            break;
          }
        }
      }
      for (let qq in memberNumsObj) {
        let obj = memberNumsObj[qq];
        let total = 0;
        for (let w = 1; w <= 16; w++) {
          total += obj["w" + w] || 0;
        }
        obj["total"] = total;
      }
      let numsList = [];
      for (let i = 0, n = members.length; i < n; i++) {
        let memItem = members[i];
        let thankCount = 0;
        let thankList = [];
        for (let name in thanksObj) {
          let thankItem = thanksObj[name];
          if (thankItem.qq === memItem.qq) {
            thankCount += thankItem.count;
            thankList.push(...thankItem.list);
          }
        }
        let obj = {
          ...memberNumsObj[memItem.qq],
          thankCount,
          thankList,
          subnames: memItem.subnames,
        };
        numsList.push(obj);
      }
      this.numsList = numsList;
      this.isShowNumsList = true;
      setTimeout(() => {
        new this.$tableSelect(".replay-wrap .table");
      }, 500);
    },
    copyNums() {
      let str = "";
      for (let i = 0, n = this.numsList.length; i < n; i++) {
        let item = this.numsList[i];
        str += `${item.total}\n`;
      }
      copy2Clipboard(str);
      this.$Message.info("复制成功!");
    },
    showThankList(item) {
      this.thankReplayList = item.thankList;
      let subnames = item.subnames.split(",").filter((str) => str);
      this.tagNames = subnames;
      this.isShowReplayFilter = true;
    },
    copyThankNums() {
      let str = "";
      for (let i = 0, n = this.numsList.length; i < n; i++) {
        let item = this.numsList[i];
        str += `${item.thankCount}\n`;
      }
      copy2Clipboard(str);
      this.$Message.info("复制成功!");
    },
  },
  mounted() {
    this.initData();
  },
  components: {
    ModalReplays,
    ModalImportWork,
    ExportReplay,
  },
};
</script>

<style></style>
